package com.ruoyi.dynamic.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.UserBalanceConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.pojo.result.PageUtils;
import com.ruoyi.common.core.pojo.result.Pages;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.dynamic.mapper.RoomQuizRecordMapper;
import com.ruoyi.dynamic.model.constant.DynamicConstant;
import com.ruoyi.dynamic.model.constant.RoomChatRoomKvConstant;
import com.ruoyi.dynamic.model.pojo.entity.Gift;
import com.ruoyi.dynamic.model.pojo.entity.Room;
import com.ruoyi.dynamic.model.pojo.entity.RoomQuizRecord;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomAuctionStartRequest;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomQuizAddRequest;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomQuizSearchRequest;
import com.ruoyi.dynamic.model.pojo.request.app.AppRoomWishCloseRequest;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomQuizResult;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomSetResult;
import com.ruoyi.dynamic.service.*;
import com.ruoyi.system.api.RemoteAppUserService;
import com.ruoyi.system.api.model.request.AppUserBalanceOpetRequest;
import com.ruoyi.system.api.model.user.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.Optional;

/**
 * <p>
 * 语聊房问答 服务实现类
 * </p>
 *
 * @author Gnc
 * @since 2024-12-26
 */
@Service
public class RoomQuizRecordServiceImpl extends ServiceImpl<RoomQuizRecordMapper, RoomQuizRecord> implements IRoomQuizRecordService {

    @Autowired
    private IGiftService giftService;
    @Autowired
    private IRoomGiftRecordService giftRecordService;
    @Autowired
    private RemoteAppUserService remoteAppUserService;
    @Autowired
    private IRoomService iRoomService;
    @Autowired
    private IMessageService messageService;


    @Override
    public void quizAdd(Long userId, AppRoomQuizAddRequest request) {
        Room room = iRoomService.verify(request.getRoomId());
        Assert.isTrue(!room.getUserId().equals(userId), "主播不可参与回答");

        AppRoomSetResult set = iRoomService.getUserRoomSet(room.getUserId());
        Assert.isTrue(set.getIsQuiz().equals(DynamicConstant.CheckStatus.YES), "未开启提问");
        Assert.isTrue(set.getQuizGiftId().equals(request.getGiftId()), "礼物不符合提问");
        Assert.isTrue(set.getIsRoomQuiz().equals(DynamicConstant.CheckStatus.YES), "未开启提问");

        R<AppUser> userInfo = remoteAppUserService.getUserInfo(userId, SecurityConstants.APP);
        AppUser data = userInfo.getData();
        Gift verify = giftService.getById(set.getQuizGiftId());
        if (!CommonUtils.isNull(verify)) {
            BigDecimal giftPrice = verify.getGiftPrice();
            AppUserBalanceOpetRequest opetRequest = new AppUserBalanceOpetRequest();
            opetRequest.setBalTypel(UserBalanceConstants.BalanceType.balance);
            opetRequest.setContent("语聊房提问");
            opetRequest.setMoney(giftPrice);
            opetRequest.setType(UserBalanceConstants.Type.Zhi);
            opetRequest.setUserId(userId);
            R<Boolean> booleanR = remoteAppUserService.docBalance(opetRequest, SecurityConstants.APP);
            Assert.isTrue(booleanR.getCode() == 2000, booleanR.getmessage());

            giftRecordService.addRecord(request.getRoomId(), room.getRoomNumber(), userId, Collections.singleton(room.getUserId()), set.getQuizGiftId(), "语聊房提问", giftPrice, 0);
        }

        RoomQuizRecord record = new RoomQuizRecord();
        record.setUserId(userId);
        record.setGiftId(set.getQuizGiftId());
        record.setGiftImg(Optional.ofNullable(verify).orElse(new Gift()).getGiftImg());
        record.setGiftNum(1);
        record.setRoomId(room.getId());
        record.setTitle(request.getTitle());
        record.setUserNickName(data.getNickName());
        record.setUserPhoto(data.getPhoto());
        record.setCreateTime(new Date());
        record.setStatus(DynamicConstant.CheckStatus.NO);
        record.setTopTime(new Date());
        save(record);

        Long count = lambdaQuery()
                .eq(RoomQuizRecord::getRoomId, room.getId())
                .ne(RoomQuizRecord::getStatus, DynamicConstant.CheckStatus.FENG)
                .count();
        if (count == 1) {
            record.setStatus(DynamicConstant.CheckStatus.YES);
            updateById(record);

            AppRoomQuizResult build = AppRoomQuizResult.builder()
                    .title(record.getTitle())
                    .status(record.getStatus())
                    .isQuiz(set.getIsQuiz())
                    .quizContent(set.getQuizContent())
                    .quizGiftId(set.getQuizGiftId())
                    .quizGiftImg(set.getQuizGiftImg())
                    .build();
            messageService.setRoomChatRoomAttr(room.getGroupId(), room.getUserId().toString(), RoomChatRoomKvConstant.ROOM_QUIZ,
                    JSONObject.toJSONString(build), 0, "", "");
        }

    }

    @Override
    public Pages<RoomQuizRecord> listPage(AppRoomQuizSearchRequest request, Long userId) {
        Page<RoomQuizRecord> roomQuizRecordPage = PageUtils.initPage(request, RoomQuizRecord.class);
        Page<RoomQuizRecord> page = lambdaQuery()
                .eq(RoomQuizRecord::getRoomId, request.getRoomId())
                .eq(!CommonUtils.isNull(request.getStatus()) && !request.getStatus().equals(0), RoomQuizRecord::getStatus, request.getStatus())
                .in(!CommonUtils.isNull(request.getStatus()) && request.getStatus().equals(0), RoomQuizRecord::getStatus, DynamicConstant.CheckStatus.NO, DynamicConstant.CheckStatus.YES)
                .orderByDesc(request.isQuiz(), RoomQuizRecord::getStatus)
                .orderByDesc(request.isQuiz(), RoomQuizRecord::getTopTime)
                .orderByDesc(!request.isQuiz(), RoomQuizRecord::getCreateTime)
                .page(roomQuizRecordPage);
        return PageUtils.pages(page);
    }

    @Override
    public boolean changeStatus(AppRoomAuctionStartRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        Assert.isTrue(verify.getUserId().equals(userId), "您无权限切换");

        RoomQuizRecord record = getById(request.getId());
        Assert.notNull(record, "记录不存在");
        Assert.isTrue(record.getStatus().equals(DynamicConstant.CheckStatus.YES), "此问答已结束!");
        record.setStatus(DynamicConstant.CheckStatus.FENG);
        updateById(record);

        AppRoomSetResult set = iRoomService.getUserRoomSet(verify.getUserId());

        RoomQuizRecord one = lambdaQuery()
                .eq(RoomQuizRecord::getStatus, DynamicConstant.CheckStatus.NO)
                .eq(RoomQuizRecord::getRoomId, request.getRoomId())
                .orderByDesc(RoomQuizRecord::getTopTime)
                .orderByAsc(RoomQuizRecord::getCreateTime)
                .last("limit 1").one();
        if (!CommonUtils.isNull(one)) {
            one.setStatus(DynamicConstant.CheckStatus.YES);
            updateById(one);

            verify.setMotion(one.getTitle());
            iRoomService.updateById(verify);
        }

        AppRoomQuizResult build = AppRoomQuizResult.builder()
                .title(Optional.ofNullable(one).orElse(new RoomQuizRecord()).getTitle())
                .status(CommonUtils.isNull(one) ? 0 : one.getStatus())
                .isQuiz(set.getIsQuiz())
                .quizContent(set.getQuizContent())
                .quizGiftId(set.getQuizGiftId())
                .quizGiftImg(set.getQuizGiftImg())
                .build();

        messageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_QUIZ,
                JSONObject.toJSONString(build), 0, "", "");
        return true;
    }

    @Override
    public boolean overGame(Long id, Long userId) {
        Room verify = iRoomService.verify(id);
        Assert.isTrue(verify.getUserId().equals(userId), "您无权限结束此游戏");

        lambdaUpdate()
                .eq(RoomQuizRecord::getRoomId, id)
                .remove();


        AppRoomQuizResult build = AppRoomQuizResult.builder()
                .title("")
                .status(DynamicConstant.CheckStatus.FENG)
                .build();

        messageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_QUIZ,
                JSONObject.toJSONString(build), 0, "", "");
        return true;
    }

    @Override
    public boolean delRecord(AppRoomAuctionStartRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        Assert.isTrue(verify.getUserId().equals(userId), "只有主播才能操作!");
        return lambdaUpdate().eq(RoomQuizRecord::getId, request.getId()).remove();
    }

    @Override
    public boolean topRecord(AppRoomAuctionStartRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        Assert.isTrue(verify.getUserId().equals(userId), "只有主播才能操作!");
        RoomQuizRecord record = getById(request.getId());
        Assert.isTrue(record.getStatus().equals(DynamicConstant.CheckStatus.NO), "当前记录正在问答中/已结束无法操作");
        record.setTopTime(new Date());
        return updateById(record);
    }

    @Override
    public void openOrStop(Integer isQuiz, Long rooomId, String quizContent, Long quizGiftId, String quizGiftImg) {
        if (!rooomId.equals(0L)) {

            RoomQuizRecord one = lambdaQuery()
                    .eq(RoomQuizRecord::getStatus, DynamicConstant.CheckStatus.YES)
                    .eq(RoomQuizRecord::getRoomId, rooomId)
                    .last("limit 1")
                    .one();

            Room verify = iRoomService.verify(rooomId);
            AppRoomQuizResult build = AppRoomQuizResult.builder()
                    .title(Optional.ofNullable(one).orElse(new RoomQuizRecord()).getTitle())
                    .isQuiz(isQuiz)
                    .quizContent(quizContent)
                    .quizGiftId(quizGiftId)
                    .quizGiftImg(quizGiftImg)
                    .build();
            messageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_QUIZ,
                    JSONObject.toJSONString(build), 0, "", "");
        }
    }

    @Override
    public boolean isUserQuiz(Long roomId, Long userId) {
        return lambdaQuery().eq(RoomQuizRecord::getUserId, userId)
                .eq(RoomQuizRecord::getRoomId, roomId)
                .count() > 0;
    }

    @Override
    public boolean closeQuiz(AppRoomWishCloseRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());

        AppRoomSetResult set = iRoomService.getUserRoomSet(verify.getUserId());
        set.setIsRoomQuiz(DynamicConstant.CheckStatus.NO);

        return false;
    }
}
